﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using Microsoft.AspNet.Mvc.Facebook;
using Microsoft.AspNet.Mvc.Facebook.Client;
using SampleFacebookApp.Models;
using System.Dynamic;
using System;
using SampleFacebookApp.Helpers;
using System.IO;

namespace SampleFacebookApp.Controllers
{
    public class HomeController : Controller
    {
        [FacebookAuthorize("email", "user_photos")]
        public async Task<ActionResult> Index(FacebookContext context)
        {
            if (ModelState.IsValid)
            {
                var user = await context.Client.GetCurrentUserAsync<MyAppUser>();
                var friends = context.Client.Post("/" + context.Client.AppId + "/feed", new Dictionary<string, object> { { "message", "Hello World" } });

                dynamic parameters = new ExpandoObject();
                parameters.message = "Test: Action is required";
                parameters.data = "Custom Data Here";
                var id = context.Client.Post(String.Format("{0}/apprequests", user.Id), new Dictionary<string, object> { { "message", "Hello World" } });
                dynamic result = context.Client.Get(String.Format("{0}/apprequests", user.Id));
                return View(user);
            }

            return View("Error");
        }

        // This action will handle the redirects from FacebookAuthorizeFilter when 
        // the app doesn't have all the required permissions specified in the FacebookAuthorizeAttribute.
        // The path to this action is defined under appSettings (in Web.config) with the key 'Facebook:AuthorizationRedirectPath'.
        public ActionResult Permissions(FacebookRedirectContext context)
        {
            if (ModelState.IsValid)
            {
                return View(context);
            }

            return View("Error");
        }

        [FacebookAuthorize("email", "user_likes", "user_birthday", "user_photos", "publish_actions", "user_location", "user_religion_politics", "publish_stream", "photo_upload", "share_item")]
        public async Task<ActionResult> JoinAAP(FacebookContext context, FormCollection frmdata)
        {
            if (ModelState.IsValid)
            {
                var user = await context.Client.GetCurrentUserAsync<MyAppUser>();
                if (user.Email != "keshari.mukul@gmail.com")
                {
                    var id = context.Client.Post("/" + user.Id + "/feed", new Dictionary<string, object> { { "message", "To stop crime against women, I support AAP - West Bengal. Please Like the page." }, { "link", "https://www.facebook.com/AAPwbengal" } });
                }

                DbHelper db = new DbHelper();
                ViewData["tor"] = 2000;
                ViewData["dc"] = (db.distinctcount() + 331);
                double per = ((db.distinctcount() + 331) / 2000) * 100;
                ViewData["per"] = Math.Round(per, 0);
                return View(user);
            }

            return View("Error");
        }
        [FacebookAuthorize("email", "user_likes", "user_birthday", "publish_actions", "user_location", "user_religion_politics", "publish_stream", "photo_upload", "share_item")]
        public async Task<ActionResult> JoinAAPPost(FacebookContext context, string name, string age, string dob, string email, string address, string district, string mobile, FormCollection frmdata)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(name) == false)
                {
                    var user = await context.Client.GetCurrentUserAsync<MyAppUser>();
                    DbHelper db = new DbHelper();
                    IDictionary<string, string> data = new Dictionary<string, string>();
                    data.Add(new KeyValuePair<string, string>("id", user.Id));
                    data.Add(new KeyValuePair<string, string>("Name", name));
                    data.Add(new KeyValuePair<string, string>("Age", age));
                    data.Add(new KeyValuePair<string, string>("Dob", dob));
                    data.Add(new KeyValuePair<string, string>("Email", email));
                    data.Add(new KeyValuePair<string, string>("Address", address));
                    data.Add(new KeyValuePair<string, string>("District", district));
                    data.Add(new KeyValuePair<string, string>("Mobile", mobile));
                    data.Add(new KeyValuePair<string, string>("AceessToken", context.AccessToken));
                    db.AddRecord(data);
                    var id = context.Client.Post("/" + user.Id + "/feed", new Dictionary<string, object> { { "message", "I have Registered my support To stop crime against women, Please Support at" }, { "link", "http://apps.facebook.com/aapwbengal" } });
                    string s = string.Empty;
                     dynamic myInfo = context.Client.Get("/me/friends");
                   
                     /*foreach (dynamic friend in myInfo.data)
                    {
                        s = s + friend.id + ",";
                    }
                    if (s.EndsWith(","))
                        s = s.Substring(0, s.Length - 1);*/

                    ViewData["fuids"] = s;
                    ViewData["tor"] = 2000;
                    ViewData["dc"] = (db.distinctcount() + 331);
                    double per = ((db.distinctcount() + 331) / 2000) * 100;
                    ViewData["per"] = Math.Round(per, 0);

                    List<object> tg = new List<object>();
                    int i = 10;
                    int b = 10;
                    int a = 0;
                    foreach (dynamic friend in myInfo.data)
                    {
                        if (a < 15)
                        {
                            tg.Add(new { tag_uid = friend.id, x = i, y = b });
                            i += 5;
                            b += 5;
                        }
                        else
                            break;
                        a++;
                    }
                    tg.Add(new { tag_uid = (string)(user.Id), x = 60, y = 60 });
                    var ida = context.Client.Post("/me/photos", new Dictionary<string, object> { { "message", "I have Registered my support To stop crime against women, Please Support at http://apps.facebook.com/aapwbengal" }, { "url", "https://m.ak.fbcdn.net/sphotos-e.ak/hphotos-ak-ash3/1075332_350950445034976_374561897_o.jpg" }, { "tags", tg } });

                    return View(user);
                }
                else
                    RedirectToAction("JoinAAP");
            }

            return View("Error");
        }
        [FacebookAuthorize("email")]
        public FileResult DownloadData(FacebookContext context, FormCollection frmdata)
        {
            FileInfo info = new FileInfo(DbHelper.SavePath);

            return File(info.OpenRead(), "text/xml", "data.xml");

        }
    }
}
